/**
 * 
 */
package org.gigi.security.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.gigi.core.Page;
import org.gigi.core.web.BasicResponse;
import org.gigi.core.web.BeanResponse;
import org.gigi.core.web.GridResponse;
import org.gigi.core.web.ListResponse;
import org.gigi.security.domain.Authority;
import org.gigi.security.domain.Group;
import org.gigi.security.domain.User;
import org.gigi.security.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户组控制层
 *
 * @author Eugene Wang 2011-8-29
 * @see
 */
@Controller
@RequestMapping("/sec/group")
public class GroupController {
	/*Logger*/
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GroupService groupService;
	/**
	 * 新创建一个用户组
	 * @param group
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public @ResponseBody BeanResponse<Group> create(@RequestBody Group group) {
		if (logger.isInfoEnabled()) {
			logger.info("创建用户组[" + group.toString()+"]");
		}
		groupService.create(group);
		BeanResponse<Group> response = new BeanResponse<Group>("成功创建用户组", group);
		return response;
	}

	/**
	 * 根据ID删除一个用户组。
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
	public @ResponseBody BasicResponse remove(@PathVariable("id") long id) {
		if (logger.isDebugEnabled()) {
			logger.debug("删除用户组>{id = " + id + "}");
		}
		groupService.delete(id);
		return new BasicResponse("成功删除用户组");
	}

	/**
	 * 修改一个用户组。
	 * @param group
	 * @return
	 */
	@RequestMapping(method=RequestMethod.PUT)
	public @ResponseBody BeanResponse<Group> update(@RequestBody Group group) {
		if (logger.isDebugEnabled()) {
			logger.debug("修改用户组>{id="+group+"; group="+group+"}");
		}
		groupService.update(group);
		BeanResponse<Group> response = new BeanResponse<Group>("成功修改用户组", group);
		return response;
	}

	/**
	 * 读取一个用户组
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/{id}",  method=RequestMethod.GET)
	public @ResponseBody BeanResponse<Group> get(@PathVariable("id") long id) {
		Group group = groupService.findById(id);
		BeanResponse<Group> response = new BeanResponse<Group>();
		response.setData(group);
		return response;
	}

	/**
	 * 获取子用户组
	 * @param parentId
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public @ResponseBody ListResponse<Group> findChildren(@RequestParam("node") long parentId) {
		List<Group> groups = groupService.findChildren(parentId);
		ListResponse<Group> response = new ListResponse<Group>("成功获取所有角色", groups);
		response.addMixInAnnotations(Group.class, ListResponseRoleFilter.class);
		return response;
	}
	@JsonIgnoreProperties( { "authorities" })
	public interface ListResponseRoleFilter {
	}

	/**
	 * 获取用户组用户用户列表（分页）
	 * @param groupId
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/{id}/users", method=RequestMethod.GET)
	public @ResponseBody GridResponse<User> getUserPage(@PathVariable("id") long groupId, Page<User> page) {
		Group group = new Group();
		group.setId(groupId);
		Page<User> resultPage = groupService.getUserPage(group, page);
		return new GridResponse<User>(resultPage);
	}

	/**
	 * 增加用户组用户
	 * @param groupId
	 * @param users
	 * @return
	 */
	@RequestMapping(value="/{id}/users", method=RequestMethod.POST)
	public @ResponseBody BasicResponse addUsers(@PathVariable("id") long groupId, @RequestBody List<Map<String, String>> pUsers) {
		Group group = new Group();
		group.setId(groupId);
		List<User> users = convertToUserList(pUsers);
		groupService.addUsers(group, users);
		BasicResponse basicResponse = new BasicResponse("成功添加用户");
		return basicResponse;
	}

	/**
	 * 删除用户组用户
	 * @param groupId
	 * @param users
	 * @return
	 */
	@RequestMapping(value="/{id}/users", method=RequestMethod.DELETE)
	public @ResponseBody BasicResponse removeUsers(@PathVariable("id") long groupId, @RequestBody List<Map<String, String>> pUsers) {
		Group group = new Group();
		group.setId(groupId);
		List<User> users = convertToUserList(pUsers);
		groupService.removeUsers(group, users);
		BasicResponse basicResponse = new BasicResponse("成功删除用户");
		return basicResponse;
	}

	private List<User> convertToUserList(List<Map<String, String>> pUsers) {
		List<User> users  = new ArrayList<User>();
		for (Map<String, String> each : pUsers) {
			User user = new User();
			user.setUsername(each.get("username"));
			users.add(user);
		}
		return users;
	}

	/**
	 * 获取不属于当前用户组的用户列表（分页）
	 * @param groupId
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/{id}/nonusers", method=RequestMethod.GET)
	public @ResponseBody GridResponse<User> getNonUserPage(@PathVariable("id") long groupId, Page<User> page) {
		Group group = new Group();
		group.setId(groupId);
		Page<User> resultPage = groupService.getNonUserPage(group, page);
		return new GridResponse<User>(resultPage);
	}
	/**
	 * 获取用户组权限。
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value="/{id}/authorities", method=RequestMethod.GET)
	public @ResponseBody ListResponse<Authority> getAuthorities(@PathVariable("id") long groupId) {
		List<Authority> authorities = groupService.findGroupAuthorities(groupId);
		return new ListResponse<Authority>("成功获取用户组权限", new ArrayList<Authority>(authorities));
	}
	/**
	 * 增加用户组权限。
	 * @param groupId
	 * @param pAuthroities
	 * @return
	 */
	@RequestMapping(value="/{id}/authorities", method=RequestMethod.POST)
	public @ResponseBody BasicResponse addAuthorities(@PathVariable("id") long groupId, @RequestBody List<Map<String, String>> pAuthroities) {
		Group group = new Group();
		group.setId(groupId);
		List<Authority> users = convertToAuthorityList(pAuthroities);
		groupService.addAuthorities(group, users);
		BasicResponse basicResponse = new BasicResponse("成功添加权限");
		return basicResponse;
	}
	/**
	 * 删除用户组权限。
	 * @param groupId
	 * @param pAuthroities
	 * @return
	 */
	@RequestMapping(value="/{id}/authorities", method=RequestMethod.DELETE)
	public @ResponseBody BasicResponse deleteAuthorities(@PathVariable("id") long groupId, @RequestBody List<Map<String, String>> pAuthroities) {
		Group group = new Group();
		group.setId(groupId);
		List<Authority> users = convertToAuthorityList(pAuthroities);
		groupService.deleteAuthorities(group, users);
		BasicResponse basicResponse = new BasicResponse("成功删除权限");
		return basicResponse;
	}
	/**
	 * 组装权限列表
	 * @param pAuthroities
	 * @return
	 */
	private List<Authority> convertToAuthorityList(
			List<Map<String, String>> pAuthroities) {
		List<Authority> authorities  = new ArrayList<Authority>();
		for (Map<String, String> each : pAuthroities) {
			Authority authority = new Authority();
			authority.setCode(each.get("code"));
			authorities.add(authority);
		}
		return authorities;
	}
}
